<template>
    <!-- 整体容器 -->
    <div class="pages">
        <el-container class="page-container">
            <!-- 搜索 -->
            <el-header class="page-header">
                <el-input style="width:300px;margin-right: 20px;" v-model.trim="input" placeholder="请输入管理员名称"
                    clearable />
                <el-button type="primary" :icon="Search" @click="handlerlookupAdmin">查找</el-button>
                <el-button type="primary" :icon="Edit" @click="handleraddAdmin">添加</el-button>
            </el-header>
            <el-main class="page-main">
                <!-- 表格 -->
                <div class="main-table">
                    <el-table :data="tableData" border  style="width: 100%">
                        <el-table-column prop="id" label="管理员ID" />
                        <el-table-column prop="username" label="管理员名称" />
                        <el-table-column prop="realname" label="真实姓名" />
                        <el-table-column prop="phone" label="电话" />
                        <el-table-column label="管理员角色">
                            <template #default="scope">
                                <el-space :size="10" wrap>
                                    <el-tag v-for="(item,index) in scope.row.roleIds" :key="index">{{handlerAdminName(item)}}</el-tag>
                                </el-space>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="160px" #default="scope">
                            <template v-if="scope.row.id != 1">
                                <el-button type="primary" @click="handlereditAdmin(scope.row)">修改</el-button>
                                <el-button type="danger" @click="handlerdeleAdmin(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页 -->
                <div class="page-pagination">
                    <Pagination v-bind="adminPagination" @handle-pagination="emitEntProps"/>
                </div>
                <!-- 回到顶部组件 -->
                <el-backtop :right="100" :bottom="100" target=".el-main" ref="refBacktop" />
                <!-- 对话框组件 -->
                <el-dialog v-model="dialogFormVisible" :title="dialogTitle" destroy-on-close width="40%">
                    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="100px"
                        class="demo-ruleForm">
                        <el-form-item label="用户名" prop="username" class="is-required">
                            <el-input v-model.trim="ruleForm.username" autocomplete="off" :disabled="dialogTitle!='创建'"/>
                        </el-form-item>
                        <el-form-item label="密码" prop="password" class="is-required" v-if="dialogTitle=='创建'">
                            <el-input v-model.trim="ruleForm.password" type="password" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="phone" class="is-required">
                            <el-input v-model.trim="ruleForm.phone" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="真实姓名" prop="realname" class="is-required">
                            <el-input v-model.trim="ruleForm.realname" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="角色" :required="dialogTitle!='创建'" :prop="dialogTitle!='创建'?'roleIds':''">
                            <el-select v-model="ruleForm.roleIds" multiple style="width: 240px">
                                <el-option v-for="(item,index) in options" :key="index" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handlersubmitForm(ruleFormRef)">
                                {{dialogTitle=='创建'?'创建':'修改'}}
                            </el-button>
                            <el-button @click="handlerresetForm(ruleFormRef)">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ClassPagination } from '#/index';
import { ref, reactive, nextTick, watch } from "vue"
import { Search, Edit } from '@element-plus/icons-vue'
import { post } from "@/utils/index";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from 'element-plus'


const ruleFormRef = ref<FormInstance>()
const refBacktop = ref()
// 搜索文本框绑定的数据
const input = ref<string>('')
/**
 * 分页的数据
 */
 let adminPagination = reactive(new ClassPagination())
// 表格数据
const tableData: TypeAdmin[] = reactive([])
// 弹出框数据
/**
 * 弹出框多选框数据渲染
 */
const options: TypeRoleIds[] = reactive([])
/**
 * 对话框默认隐藏,true为显示,false为隐藏
 */
const dialogFormVisible = ref(false)
/**
 * 对话框title默认为创建
 */
const dialogTitle = ref<string>("创建")
/**
 * 搜索传递的参数变量
 */
const lookupName = ref<string>('')
/**
 * 获取表单的数据
 */
const getFormData:TypeAdminForm[] = reactive([])
/**
 * 弹出框表单数据
 */
let ruleForm: TypeAdminForm = reactive({
    username: '',
    password: '',
    phone: '',
    realname: '',
    roleIds: [],
    id:0,
})
/**
 * 获取表单的空值
 */ 
const addAdminLimt = {...ruleForm}

// 使用findIndex差找数据，处理管理员角色数据
function handlerAdminName (val:number) {
    let text = options.findIndex(item=>item.value == val)
    return options[text].label||''
}

/**
 * 表单用户名验证
 * @param rule
 * @param value
 * @param callback
 */
function validateUser (rule: Object, value: string, callback: Function) {
    let user = /^[a-zA-Z0-9_]{4,16}$/;
    if(dialogTitle.value == "创建"){
        if (!value) {
            return callback(new Error('用户名不能为空'))
        } else if (!user.test(value)) {
            return callback(new Error('用户名是4到16位字母,数字,下划线'))
        } else {
            callback()
        }
    }else{
        callback()
    }
}
/**
 * 密码验证
 * @param rule
 * @param value
 * @param callback
 */
function validatePass (rule: Object, value: string, callback: Function) {
    let pass = /^[a-zA-Z0-9_-]{4,16}$/;
    if (value === '') {
        callback(new Error('密码不能为空'))
    } else if(!pass.test(value)){
        callback(new Error('密码是4到16位字母,数字,下划线,减号'))
    }else{
        callback()
    }
}
/**
 * 电话号码验证
 * @param rule
 * @param value
 * @param callback
 */
function validatePhone (rule: Object, value: string, callback: Function) {
    var phone = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
    if (value === '') {
        callback(new Error('电话号码不能为空'))
    }else if(!phone.test(value)){
        callback(new Error('电话号码不存在'))
    } else {
        callback()
    }
}
/**
 * 真实姓名验证
 * @param rule
 * @param value
 * @param callback
 */
function validateRealName (rule: Object, value: string, callback: Function) {
    let cnPattern = /^[\u4E00-\u9FA5]{2,4}$/;
    if (value === '') {
        callback(new Error('真实姓名不能为空'))
    } else if(!cnPattern.test(value)){
        callback(new Error('真实姓名必须是2-4位中文'))
    } else {
        callback()
    }
}
/**
 * 角色验证
 * @param rule
 * @param value
 * @param callback
 */
function validateRoleIds (rule: Object, value: string, callback: Function) {
    if (value.length === 0) {
        callback(new Error('角色不能为空'))
    } else {
        callback()
    }
}
/**
 * 绑定验证规则，定义触发方式
 */
const rules = reactive({
    username: [{ validator: validateUser, trigger: 'blur' }],
    password: [{ validator: validatePass, trigger: 'blur' }],
    phone: [{ validator: validatePhone, trigger: 'blur' }],
    realname: [{ validator: validateRealName, trigger: 'blur' }],
    roleIds: [{ validator: validateRoleIds, trigger: 'change' }],
})
/**
 * 确认提交
 * @param formEl
 */
function handlersubmitForm (formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
                let data = {
                    _gp:'admin',
                    _mt:dialogTitle.value=='创建'?'create':'edit',
                    adminDTO:JSON.stringify({...ruleForm})
                }
                post(data).then((res) => {
                    console.log(res);
                    if(200 === res.errno){
                        getAdminList()
                        dialogFormVisible.value = false
                        ElMessage.success(dialogTitle.value=='创建'?"创建成功":"修改成功")
                    }else{
                        ElMessage.error(res.errmsg)
                    }
                })
        } else {
            return false
        }
    })
}
/**
 * 获取管理员数据
 */
function getAdminList () {
    let data = {
        _gp: 'admin',
        _mt: 'list',
        username: lookupName.value,   //查询的值
        page: adminPagination.page,  //第几页
        limit: adminPagination.limit //获取的条数
    }
    // 表格数据
    post(data).then((res) => {
        if (200 === res.errno) {
            return Promise.resolve(res.data)
        } else {
            return Promise.reject(res.errmsg)
        }
    }).then((resLimt) => {
        // 枚举数据
        post({
            _gp: 'admin.role',
            _mt: 'options'
        }).then((res) => {
            let { items, total } = resLimt
            tableData.length = 0    //清零
            tableData.push(...items)
            adminPagination.total = total   // 获取总条数
            // 枚举数据
            options.length = 0  //清零
            options.push(...res.data)  // 获取角色枚举的数据，用于渲染对话框的选择框
        })
    }).catch(err => {
        tableData.length = 0
        ElMessage.error(err)
    })
}
/**
 * 查找管理员
 */
function handlerlookupAdmin () {
    lookupName.value = input.value
    adminPagination.page = 1
    getAdminList()
}
/**
 * 添加管理员
 */
function handleraddAdmin () {
    dialogTitle.value = '创建'
    dialogFormVisible.value = true
    Object.assign(ruleForm, addAdminLimt)  // 清空输入框
}
/**
 * 编辑管理员
 * @param row
 */
function handlereditAdmin (row:TypeAdmin) {
    dialogTitle.value = '编辑';
    dialogFormVisible.value = true;
    ruleForm.username =  row.username;
    ruleForm.password = undefined;
    ruleForm.phone =  row.phone;
    ruleForm.realname =  row.realname;
    ruleForm.roleIds = row.roleIds;
    ruleForm.id = row.id;
    Object.assign(getFormData,row)
}
/**
 * 删除管理员
 * @param row
 */
function handlerdeleAdmin (row:TypeAdmin) {
    ElMessageBox.confirm(
        '确认是否删除?',
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }
    ).then(() => {
        let data = {
                _gp:'admin',
                _mt:'delete',
                id:row.id
            }
        post(data).then((res) => {
            if (200 === res.errno) {
                getAdminList()
                ElMessage.success("删除成功")
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }).catch(() => {
        ElMessage.warning("已取消删除")
    })
    
}
/**
 * 重置表单
 * @param formEl
 */
function handlerresetForm (formEl: FormInstance | undefined) {
    if (!formEl) return
    dialogTitle.value=='创建'? Object.assign(ruleForm, addAdminLimt):Object.assign(ruleForm, getFormData)
    formEl.resetFields()
}
/**
 * 分页组件传递过来的数据
 * @param val
 * page:页数
 * limit:条数
 */
 function emitEntProps(val: { page: number, limit: number }) {
    let paging = adminPagination
    paging.page = val.page
    paging.limit = val.limit
    getAdminList()
}

// 第一次渲染
getAdminList()
</script>

<style lang="less" scoped>
/deep/.el-form-item__content:first-child {
    justify-content: right;
}
.el-input{
    width: 90%;
}
</style>